package org.ttjhome.html.struts.candidate;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.actions.DispatchAction;
import org.json.JSONArray;
import org.json.JSONObject;
import org.ttjhome.db.CandidateCriteriaHelper;
import org.ttjhome.db.dbo.Activity;
import org.ttjhome.db.dbo.ActivityRecord;
import org.ttjhome.db.dbo.Candidate;
import org.ttjhome.db.dbo.Job;
import org.ttjhome.db.dbo.Resume;
import org.ttjhome.db.dbo.Tag;
import org.ttjhome.db.dbo.User;
import org.ttjhome.html.struts.ActionMessageRegistry;
import org.ttjhome.html.struts.common.CandidateCriteria;
import org.ttjhome.html.struts.common.GENDER;
import org.ttjhome.html.struts.common.SecurityConstants;
import org.ttjhome.html.struts.util.TagsCache;
import org.ttjhome.server.HunterServiceFactory;
import org.ttjhome.util.StringUtils;





public class CandidatesAction extends DispatchAction {

	private static final Logger logger = Logger.getLogger(CandidatesAction.class
			.getName());
//    static
//    {
//        PropertyConfigurator.configureAndWatch("D://work//deploy//tomcat-5.5.31//webapps//simpleHunter//WEB-INF//classes//log4j.properties", 10000);
//        System.out.println("fffff");
//        final String LOG_LAYOUT_PATTERN = "%m%n";
//        
//        PatternLayout layout = new PatternLayout(LOG_LAYOUT_PATTERN);
//        try {
//			Appender appender = new  DailyRollingFileAppender(layout, "D://work//deploy//tomcat-5.5.31//ff.logger", "'.'yyyy-MM-dd");
//			
//			logger.addAppender(appender);
//			logger.setLevel(Level.INFO);
//        } catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//        
//    } 
	
	public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		return list(mapping, form, request, response);
	}

	public ActionForward list(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		logger.info("Entering execute of CandidatesAction with form"+form);
		ActionForward actionForward = mapping.findForward("success");
		String jobId = request.getParameter("jobId");
		
		DynaActionForm queryForm = (DynaActionForm) form;
		if(jobId!=null&&jobId.length()>0){
			queryForm.set("jobId", jobId);
		}
		CandidateCriteria criteria= createCriteria(request, queryForm);
		ActionMessages actionMessages = new ActionMessages();
		if (!actionMessages.isEmpty())
		{
			actionMessages.add("pageerror",  new ActionMessage( "ERR_PROBLEM_IN_INPUT" ));
			request.setAttribute("ACTION_MESSAGES", actionMessages);
			return mapping.findForward("success");
		}
		 
		//get the count of all search results 
		int totalResultsCount = HunterServiceFactory.createHunterService().getCandidateCount(criteria);

		if (totalResultsCount > 0)
		{
			// get all search results for page display (include the page number)
			List<Candidate> listByPage = HunterServiceFactory.createHunterService().getCandidates(criteria);
			request.setAttribute(Constants.ATTR_CANDIDATES_LIST, listByPage);
			request.setAttribute(Constants.ATTR_CANDIDATES_COUNT, totalResultsCount);
			
		}
		else
		{
			logger.finer("not found!");
		}

		//init the query form field value for display
		initQueryForm(request, queryForm);
		
		

		return actionForward;
	}
	
	
	public ActionForward match(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		logger.info("Entering execute match of CandidatesAction with form"+form);
		ActionForward actionForward = mapping.findForward("success");
		
		DynaActionForm queryForm = (DynaActionForm) form;
		String jobId = request.getParameter("jobId");
		ActionMessages actionMessages = new ActionMessages();
		//get job first 
		Job job = HunterServiceFactory.createHunterService().getJob(Long.valueOf(jobId));
		if(job==null){
			logger.info("Job not found for job id ["+jobId+"]");
			actionMessages.add("pageerror",  new ActionMessage( "ERR_PROBLEM_IN_INPUT" ));
		}
			
		CandidateCriteria criteria= new CandidateCriteria();
		criteria.setTags(job.getTags());
		if (!actionMessages.isEmpty())
		{
			actionMessages.add("pageerror",  new ActionMessage( "ERR_PROBLEM_IN_INPUT" ));
			request.setAttribute("ACTION_MESSAGES", actionMessages);
			return mapping.findForward("success");
		}
		 
		//get the count of all search results 
		int totalResultsCount = HunterServiceFactory.createHunterService().getCandidateCount(criteria);

		if (totalResultsCount > 0)
		{
			// get all search results for page display (include the page number)
			List<Candidate> listByPage = HunterServiceFactory.createHunterService().getCandidates(criteria);
			request.setAttribute(Constants.ATTR_CANDIDATES_LIST, listByPage);
			request.setAttribute(Constants.ATTR_CANDIDATES_COUNT, totalResultsCount);
			
		}
		else
		{
			logger.finer("not found!");
		}

		//init the query form field value for display
		initQueryForm(request, queryForm);
		
		

		return actionForward;
	}
	
	
	private CandidateCriteria createCriteria(HttpServletRequest request,
			DynaActionForm queryForm) {
		CandidateCriteria criteria = new CandidateCriteria();
		String experienceType = (String) request.getParameter("experience");
		String genderType = (String) request.getParameter("gender");
		
		if(genderType!=null&&genderType.length()>0)
		{
			if(genderType.equalsIgnoreCase("male"))
				criteria.setGender(GENDER.male.name());
			else
				criteria.setGender(GENDER.female.name());
		}
		if(experienceType!=null&&experienceType.length()>0)
		{
			CandidateCriteriaHelper.resolveCriteriaType(experienceType,criteria);
		}
		String tags = (String) request.getParameter("tags");
		if(tags!=null&&tags.length()>0){
			String[] inputTags = tags.split(",");
			for(String inputTag:inputTags){
				Tag tag = TagsCache.getTag(inputTag);
				if(tag!=null){
					criteria.getTags().add(tag);
				}
			}
		}
		
		return criteria;
	}

	public ActionForward create(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
	{
	
		logger.info("Entering create of CandidatesAction with form"+form);
		ActionForward actionForward = mapping.findForward("success");
		DynaActionForm createForm = (DynaActionForm) form;
		User user = SecurityConstants.gSessionAccount.get(request);
		ActionMessages actionMessages = new ActionMessages();
		String filter = (String) createForm.get(Constants.KEY_FILTER); 
		
		if (!StringUtils.isEmpty(filter))
		{
			if (!isTokenValid(request, true))
			{
				resetToken(request);
				return mapping.findForward(Constants.FORWARD_LIST);
			}
			verifyCandidateForm(actionMessages,createForm);
			if (!actionMessages.isEmpty())
			{
				actionMessages.add(Constants.PAGE_ERROR, ActionMessageRegistry.PAGE_ERROR);
				request.setAttribute(Constants.ACTION_MESSAGES, actionMessages);
				saveToken(request);
				return mapping.findForward(Constants.FORWARD_FAILURE);
			}
			
			Candidate candidate = new Candidate();
			copyFormValueTocandidate(request,candidate, createForm,user);
			try
			{
				candidate = HunterServiceFactory.createHunterService().saveCandidate(candidate);
			}catch(Exception e)
			{
				actionMessages.add(Constants.PAGE_ERROR, ActionMessageRegistry.PAGE_ERROR);
				request.setAttribute(Constants.ACTION_MESSAGES, actionMessages);
				saveToken(request);
				return mapping.findForward(Constants.FORWARD_FAILURE);
			}
			
			request.setAttribute(Constants.ATTR_SUCCESS_MESSAGE_TYPE, Constants.ATTR_SUCCESS_MESSAGE_TYPE_SAVING);
			request.setAttribute(Constants.ATTR_SUCCESS_CANDIDATE,candidate);
			actionForward = mapping.findForward(Constants.FORWARD_LIST);
			createForm.set(Constants.KEY_FILTER, "");
		}else
		{	
			saveToken(request);
			createForm.set(Constants.KEY_FILTER, Constants.KEY_FILTER_CREATE);	
		}
		
		return actionForward;
	}
	 
	
	public ActionForward edit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
	{
	
		logger.info("Entering edit of CandidatesAction with form"+form);
		ActionForward actionForward = mapping.findForward("success");
		DynaActionForm editForm = (DynaActionForm) form;
		User user = SecurityConstants.gSessionAccount.get(request);
		ActionMessages actionMessages = new ActionMessages();
		String filter = (String) editForm.get(Constants.KEY_FILTER); 
		String candidateId=(String)editForm.get(Constants.INPUT_CANDIDATE_ID);
		
		if (StringUtils.isEmpty(candidateId))
		{
			logger.info("The candidateId is missing, rediect to candidate list page!");
			return mapping.findForward(Constants.FORWARD_LIST);
		}
		
		Candidate candidate = HunterServiceFactory.createHunterService().getCandidate(Long.valueOf(candidateId));
		
		if (!StringUtils.isEmpty(filter))
		{
			if (!isTokenValid(request, true))
			{
				resetToken(request);
				return mapping.findForward(Constants.FORWARD_LIST);
			}
			verifyCandidateForm(actionMessages,editForm);
			if (!actionMessages.isEmpty())
			{
				actionMessages.add(Constants.PAGE_ERROR, ActionMessageRegistry.PAGE_ERROR);
				request.setAttribute(Constants.ACTION_MESSAGES, actionMessages);
				saveToken(request);
				return mapping.findForward(Constants.FORWARD_FAILURE);
			}
			
			copyFormValueTocandidate(request,candidate, editForm,user);
			try
			{
				candidate = HunterServiceFactory.createHunterService().saveCandidate(candidate);
			}catch(Exception e)
			{
				actionMessages.add(Constants.PAGE_ERROR, ActionMessageRegistry.PAGE_ERROR);
				request.setAttribute(Constants.ACTION_MESSAGES, actionMessages);
				saveToken(request);
				return mapping.findForward(Constants.FORWARD_FAILURE);
			}
			logger.info("Updated Candidate "+candidate.getName() +" successfully ");
			request.setAttribute(Constants.ATTR_SUCCESS_MESSAGE_TYPE, Constants.ATTR_SUCCESS_MESSAGE_TYPE_SAVING);
			request.setAttribute(Constants.ATTR_SUCCESS_CANDIDATE,candidate);
			actionForward = mapping.findForward(Constants.FORWARD_LIST);
			editForm.set(Constants.KEY_FILTER, "");
		}else
		{	
			saveToken(request);
			editForm.set(Constants.KEY_FILTER, Constants.KEY_FILTER_EDIT);	
			copyCandidateToForm(candidate, editForm, request);
			if(candidate.getResumes()!=null&&candidate.getResumes().size()>0)
			{
				request.setAttribute(Constants.INPUT_CANDIDATE_RESUMES, candidate.getResumes().toArray());
			}
			if(candidate.getTags()!=null&&candidate.getTags().size()>0)
			{
				List<Tag> tags = new ArrayList<Tag>();
				tags.addAll(candidate.getTags());
				request.setAttribute(Constants.INPUT_CANDIDATE_TAGS, tags.toArray());
			}
			
		}
		
		return actionForward;
	}
	 
	
	public ActionForward getAllTags(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		List<Tag> tags = HunterServiceFactory.createHunterService().getAllTags();
		JSONObject json = new JSONObject();
		JSONArray array  = new JSONArray(tags);
		
		json.put("result", 0);
		json.put("data", array);
		response.setContentType("application/json");
		response.getWriter().write(json.toString());
		return null;
	}
	
	public ActionForward groupAllTags(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		List<Tag> tags = HunterServiceFactory.createHunterService().groupTag();
		JSONObject json = new JSONObject();
		JSONArray array  = new JSONArray();
		
		for(Tag tag:tags){
			JSONObject tmp = new JSONObject();
			tmp.put("tag",tag.getTag());
			tmp.put("count", tag.getCount());
			array.put(tmp);
		}
		json.put("result", 0);
		json.put("data", array);
		response.setContentType("application/json");
		response.getWriter().write(json.toString());
		return null;
	}
	
	public ActionForward apply(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		logger.info("Entering apply of CandidatesAction");
		String jobId = request.getParameter("jobId");
		String candidateId = request.getParameter("candidateID");
		logger.info("apply candidate"+candidateId+" to job"+jobId);
		Job job = HunterServiceFactory.createHunterService().getJob(
				Long.valueOf(jobId));
		Candidate candidate = HunterServiceFactory.createHunterService()
				.getCandidate(Long.valueOf(candidateId));
		List<Activity> activities = HunterServiceFactory.createHunterService().apply(candidate,job);
		JSONObject json =translateActivitiesToJson(activities);
		
		response.setContentType("application/json");
		response.getWriter().write(json.toString());

		return null;
	}
	
	
	private JSONObject translateActivitiesToJson(Collection<Activity> activities) throws Exception{
		
		JSONObject json = new JSONObject();
		JSONArray array  = new JSONArray();
		
		for(Activity activity:activities){
			JSONObject tmp = new JSONObject();
			JSONArray records = new JSONArray();
			//sort
			List<ActivityRecord> activityRecords = new ArrayList<ActivityRecord>();
			activityRecords.addAll(activity.getRecords());
			Collections.sort(activityRecords,new ActivityRecordComparator());
			
			for(ActivityRecord record :activityRecords){
				JSONObject recordJSON = new JSONObject();
				if(record.getRecordTime()!=null)
					recordJSON.put("recordTime", record.getRecordTime().toString());
				else
					recordJSON.put("recordTime", "Unknown time");
				if(record.getActivityTime()!=null)
					recordJSON.put("activityTime", record.getActivityTime().toString());
				recordJSON.put("record", record.getRecord());
				records.put(recordJSON);
			}
			tmp.put("id", activity.getId());
			tmp.put("status",activity.getStatus());
			tmp.put("companyName", activity.getJob().getCompany().getName());
			tmp.put("jobName", activity.getJob().getName());
			tmp.put("candidateName", activity.getCandidate().getName());
			tmp.put("candidateId", activity.getCandidate().getId());
			tmp.put("records", records);

			array.put(tmp);
		}
		json.put("result", 0);
		json.put("data", array);
		return json;
	}
	
	public ActionForward listActivities(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		logger.info("Entering listActivities of CandidatesAction");
		String candidateID = request.getParameter("candidateID");
		logger.info("listActivities candidateID"+candidateID);
		Candidate candidate = HunterServiceFactory.createHunterService().getCandidate(Long.valueOf(candidateID));
		if(candidate==null){
			logger.info(" candidate not found");
			return null;
		}
		List<Activity> activities = HunterServiceFactory.createHunterService().getActivities(candidate);
		JSONObject json =translateActivitiesToJson(activities);
		response.setContentType("application/json");
		response.getWriter().write(json.toString());

		return null;
	} 
	
	public ActionForward closeActivity(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		logger.info("Entering closeActivity of CandidatesAction");
		String activityId = request.getParameter("activityId");
		logger.info("closeActivity id"+activityId);
		
		List<Activity> activities = HunterServiceFactory.createHunterService().closeActivity(activityId);
		JSONObject json =translateActivitiesToJson(activities);
		response.setContentType("application/json");
		response.getWriter().write(json.toString());

		return null;
	}
	
	
	public ActionForward newProgress(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		logger.info("Entering newProgress of CandidatesAction");
		String activityId = request.getParameter("activityId");
		String newProgress = request.getParameter("newProgress");
		logger.info("new Progress activity id"+activityId +" new progress: "+newProgress);

		Activity activity = HunterServiceFactory.createHunterService()
				.getActivity(activityId);
		ActivityRecord record = new ActivityRecord();
		record.setActivity(activity);
		record.setRecordTime(new Date());
		record.setRecord(newProgress);
		record = HunterServiceFactory.createHunterService().saveOrUpdateActivityRecord(record);
		activity.getRecords().add(record);
		List<Activity> activities = HunterServiceFactory.createHunterService().getActivities(activity.getCandidate());
		JSONObject json =translateActivitiesToJson(activities);
		response.setContentType("application/json");
		response.getWriter().write(json.toString());

		return null;
	}
	
	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String resumeId = request.getParameter("id");
		Resume resume = HunterServiceFactory.createHunterService().getResume(
				resumeId);
		
		if(resume==null) return null;
		
		Candidate candidate = resume.getCandidate();
		
		candidate.getResumes().remove(resume);
		
		HunterServiceFactory.createHunterService().deleteResume(resume);
	
		JSONObject json = new JSONObject();
		JSONArray array  = new JSONArray();
		
		json.put("result", 0);
		
		for(Resume data:candidate.getResumes()){
			JSONObject tmp = new JSONObject();
			tmp.put("filename",data.getFilename());
			tmp.put("url", data.getUrl());
			tmp.put("id", data.getId());
			array.put(tmp);
		}
		json.put("data", array);
		response.setContentType("application/json");
		response.getWriter().write(json.toString());
		return null;
	}
	
	
	private void copyCandidateToForm(Candidate candidate,
			DynaActionForm editForm, HttpServletRequest request) {
		SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
		
		editForm.set(Constants.INPUT_CANDIDATE_NAME, candidate.getName());
		editForm.set(Constants.INPUT_CANDIDATE_GENDER, candidate.getGender());
		editForm.set(Constants.INPUT_CANDIDATE_ID,String.valueOf(candidate.getId()));
		editForm.set(Constants.CANDIDATE_IDNUMBER,candidate.getIdNumber());
		editForm.set(Constants.INPUT_CANDIDATE_MAILBOX, candidate.getMailAddress());
		if(candidate.getBirthDay()!=null)
			editForm.set(Constants.INPUT_CANDIDATE_BIRTHDAY, formatter.format(candidate.getBirthDay()));
		if(candidate.getWorkFrom()!=null)
			editForm.set(Constants.INPUT_CANDIDATE_WORKFROM, formatter.format(candidate.getWorkFrom()));
		
		
		
	}

	private void copyFormValueTocandidate(HttpServletRequest request, Candidate candidate,
			DynaActionForm form, User user) {
		String candidateName = form.getString(Constants.INPUT_CANDIDATE_NAME);
		String candidateGender = form.getString(Constants.INPUT_CANDIDATE_GENDER);
		String candidateBirthday = form.getString(Constants.INPUT_CANDIDATE_BIRTHDAY);
		String candidateIDNumber = form.getString(Constants.CANDIDATE_IDNUMBER);
		String candidateMailAddress = form.getString(Constants.INPUT_CANDIDATE_MAILBOX);
		String candidateWorkFrom = form.getString(Constants.INPUT_CANDIDATE_WORKFROM);
		String[] candidateResumes = form.getStrings(Constants.INPUT_CANDIDATE_RESUMES);
		String[] candidateResumeNames = form.getStrings(Constants.INPUT_CANDIDATE_RESUMESNAMES);
		String[]  tags = form.getStrings(Constants.INPUT_CANDIDATE_TAGS);
		
		//have to rename file to candidate's directory
		String 	contextPath =this.getServlet().getServletContext().getRealPath("");
		for(int i =0;i<candidateResumes.length;i++)
		{
			candidateResumeNames[i] = StringUtils.removeWhiteSpace(candidateResumeNames[i]);
			String realfilepath =contextPath+"/upload/Filedata/"+candidateResumeNames[i];
			logger.info("In copyFormValueTocandidate realfilepath "+realfilepath);
			//check if resume already added 
			boolean exists=false;
			for(Resume resume:candidate.getResumes())
			{
				if(candidateResumeNames[i].equalsIgnoreCase(resume.getFilename()))
				{
					logger.info("resume "+candidateResumeNames[i] +" has already uploaded");
					exists=true;
					break;
				}
					
			}
			//new directory
			try{
				String renameTo=contextPath+"/upload/"+candidateMailAddress;
				
				File file = new File(realfilepath);
				//in edit model,the resume that already uploaded in previous operation should not be found under filedata directory
				//unless,you uploaded a new resume with the same name, at this time, we only need to rename the file and should not 
				//add a new resume record
				if(!file.exists()) continue;
				File renameToPath = new File(renameTo);
				if(!renameToPath.exists()) renameToPath.mkdirs();
				file.renameTo(new File(renameTo+"/"+candidateResumeNames[i]));
				logger.info("move file "+candidateResumeNames[i]+ " to "+renameTo+" successfully");
				if(exists) continue;
				
			}catch(Throwable t){
				logger.info("Fatal error in rename uploaded file "+t);
			}
			Resume resume = new Resume(request.getContextPath()+"/upload/"+candidateMailAddress+"/"+candidateResumeNames[i]);
			resume.setCandidate(candidate);
			resume.setFilename(candidateResumeNames[i]); 
			candidate.getResumes().add(resume);
		}
		candidate.setName(candidateName);
		candidate.setGender(candidateGender);
		candidate.setIdNumber(candidateIDNumber);
		candidate.setMailAddress(candidateMailAddress);
		SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
		try {
			Date date = formatter.parse(candidateBirthday);
			candidate.setBirthDay(date);
		} catch (ParseException e) {
			logger.info("birthday invalid,should not happen because we already validate ");
		}
		if(candidateWorkFrom!=null)
		try {
			Date date = formatter.parse(candidateWorkFrom);
			candidate.setWorkFrom(date);
		} catch (ParseException e) {
			logger.info("workfrom invalid,should not happen because we already validate ");
		}
		//tags
		//clear first 
		candidate.getTags().clear();
		for(int i=0;i<tags.length;i++)
		{
			Tag tag = TagsCache.getTag(tags[i]);
			if(tag==null)
			{
				//add a new one 
				logger.info("Save new Tag "+tags[i]);
				tag = HunterServiceFactory.createHunterService().saveTag(tags[i]);
			}
			
			candidate.getTags().add(tag);
		}
		
		
	}

	private void verifyCandidateForm(ActionMessages actionMessages,
			DynaActionForm createForm) {
		String candidateName = createForm.getString(Constants.INPUT_CANDIDATE_NAME);
		String candidateGender = createForm.getString(Constants.INPUT_CANDIDATE_GENDER);
		String candidateBirthday = createForm.getString(Constants.INPUT_CANDIDATE_BIRTHDAY);
		String candidateWorkFrom = createForm.getString(Constants.INPUT_CANDIDATE_WORKFROM);
		String candidateIDNumber = createForm.getString(Constants.CANDIDATE_IDNUMBER);
		String candidateMailAddress = createForm.getString(Constants.INPUT_CANDIDATE_MAILBOX);
		String[] candidateResumes = createForm.getStrings(Constants.INPUT_CANDIDATE_RESUMES);
		if(StringUtils.isEmpty(candidateName))
		{
			actionMessages.add(Constants.INPUT_ERRORS, ActionMessageRegistry.CANDIDATE_NAME_INVALID);
			actionMessages.add(Constants.INPUT_CANDIDATE_NAME, ActionMessageRegistry.CANDIDATE_NAME_INVALID);
		}
		if(StringUtils.isEmpty(candidateGender))
		{
			actionMessages.add(Constants.INPUT_ERRORS, ActionMessageRegistry.CANDIDATE_GENDER_INVALID);
			actionMessages.add(Constants.INPUT_CANDIDATE_GENDER, ActionMessageRegistry.CANDIDATE_GENDER_INVALID);
		}
		if(StringUtils.isEmpty(candidateMailAddress))
		{
			actionMessages.add(Constants.INPUT_ERRORS, ActionMessageRegistry.CANDIDATE_EMAILADDRESS_INVALID);
			actionMessages.add(Constants.INPUT_CANDIDATE_MAILBOX, ActionMessageRegistry.CANDIDATE_EMAILADDRESS_INVALID);
		}else{
			//check unique value
			
		}
		if(StringUtils.isEmpty(candidateBirthday))
		{
			actionMessages.add(Constants.INPUT_ERRORS, ActionMessageRegistry.CANDIDATE_BIRTHDAY_INVALID);
			actionMessages.add(Constants.INPUT_CANDIDATE_BIRTHDAY, ActionMessageRegistry.CANDIDATE_BIRTHDAY_INVALID);
		}else
		{
			SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
			try {
				formatter.parse(candidateBirthday);
			} catch (ParseException e) {
				actionMessages.add(Constants.INPUT_ERRORS, ActionMessageRegistry.CANDIDATE_BIRTHDAY_INVALID);
				actionMessages.add(Constants.INPUT_CANDIDATE_BIRTHDAY, ActionMessageRegistry.CANDIDATE_BIRTHDAY_INVALID);
			}
		}
		if(!StringUtils.isEmpty(candidateWorkFrom))
		{
			SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
			try {
				formatter.parse(candidateWorkFrom);
			} catch (ParseException e) {
				actionMessages.add(Constants.INPUT_ERRORS, ActionMessageRegistry.CANDIDATE_WORKFROM_INVALID);
				actionMessages.add(Constants.INPUT_CANDIDATE_WORKFROM, ActionMessageRegistry.CANDIDATE_WORKFROM_INVALID);
			}
		}
		
		
	}


	public static void initQueryForm(HttpServletRequest request, DynaActionForm queryForm) {
		
	}

	public class ActivityRecordComparator implements Comparator<ActivityRecord> {

		 public int compare(ActivityRecord o1, ActivityRecord o2) {
			 if(o1.getActivityTime()!=null&&o2.getActivityTime()!=null){
				 return o1.getActivityTime().compareTo(o2.getActivityTime());
			 }
			 return o1.getRecordTime().compareTo(o2.getRecordTime());
		 }
		}
}
